<?php

namespace app\api\middleware;
use app\common\service\Result;
use app\api\model\App as AppModel;
use app\api\model\user\User;
class Auth
{
    protected $request;
    /** @var array $store 商家登录信息 */

    public function handle($request, \Closure $next)
    {
        try {
            $this->request = $request;
            //  验证登录状态
            $this->checkLogin();
            return $next($this->request);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }
    /**
     * 验证登录状态
     */
    private function checkLogin()
    {
        $this->request->user = [];
        $this->request->app = [];
        $this->request->app_id = 0;
        $this->request->user_id = 0;
        $app_id = Request()->header('appid');
        if (!$app_id) {
            throw new \Exception('应用参数错误');
        }
        $app = AppModel::detail($app_id);
        if (!$app) {
            throw new \Exception('应用信息错误');
        }
        $this->request->app = $app->toArray();
        $this->request->app_id = $app_id;
        $token = Request()->header('token');
        if (!$token) {
            $token = Request()->param('token');
        }
        if ($token) {
            $user = User::getUser($token);
            if ($user && $user->user_id && $user->app_id == $app_id && $user->is_delete == 0) {
                $this->request->user = $user->toArray();
                $this->request->user_id = $user['user_id'];
            }
        }
        return true;
    }
}